//
//  ZYQScrollView.m
//  Four_years
//
//  Created by 张跃骞 on 15/11/9.
//  Copyright © 2015年 中软三班四年小组. All rights reserved.
//
#import "ZYQScrollViewController.h"
#import "NaviBarSegmentedControl.h"

#define Seg_Y 34.5
#define Seg_Height 1.5f

@interface ZYQScrollViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) UISegmentedControl *NBSegmentedControl;
@property (strong, nonatomic) UIView *sliderView;

@end

@implementation ZYQScrollViewController

- (instancetype)initWithItems:(NSArray *)items {
    if (self = [super init]) {
        _items = items;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationBar];
    [self initScrollView];
}

- (void)initNavigationBar {
    _NBSegmentedControl = [[NaviBarSegmentedControl alloc] initWithItems:_items addTarget:self action:@selector(valueChanged:)];
    
    //跟随滑动条
    _sliderView = [[UIView alloc] initWithFrame:CGRectMake(0, Seg_Y, Seg_Width, Seg_Height)];
    _sliderView.backgroundColor = [UIColor colorWithWhite:1 alpha:.38];
    _sliderView.layer.cornerRadius = 8;
    [_NBSegmentedControl addSubview:_sliderView];
    
    self.navigationItem.titleView = _NBSegmentedControl;
}

- (void)initScrollView {
    //初始化滚动视图
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
//    _scrollView.backgroundColor = [UIColor purpleColor];
    _scrollView.contentSize = CGSizeMake(WIDTH * _items.count, 0);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.bounces = NO;
    
//    UIView *test = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
//    test.backgroundColor = [UIColor redColor];
//    [_scrollView addSubview:test];
    [self.view addSubview:_scrollView];
}

#pragma mark - 关联SegmentedControll和ScrollView

- (void)valueChanged:(UISegmentedControl *)sender {
        [_scrollView setContentOffset:CGPointMake(sender.selectedSegmentIndex * WIDTH,  -NaviBar_Height) animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        float indexf = _scrollView.contentOffset.x / WIDTH;
        _sliderView.frame = CGRectMake(indexf * Seg_Width + .5, Seg_Y, Seg_Width, Seg_Height);
        if (indexf - (int)indexf < CGFLOAT_MIN /*浮点数判断*/ ) {
            _NBSegmentedControl.selectedSegmentIndex = (int)indexf;
        }
    }
}

@end
